package com.dev.op.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dev.op.VO.ResultVO;
import com.dev.op.VO.UserVO;
import com.dev.op.entity.User;
import com.dev.op.entity.UserGroup;
import com.dev.op.entity.UserGroupAdmin;
import com.dev.op.entity.UserGroupMember;
import com.dev.op.enums.ResultCode;
import com.dev.op.exceptions.BizException;
import com.dev.op.service.UserGroupAdminService;
import com.dev.op.service.UserGroupMemberService;
import com.dev.op.service.UserGroupService;
import com.dev.op.util.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@PreAuthorize("hasAnyRole('admin','teacher','student')")
@RestController
@RequestMapping("/user-groups")
public class UserGroupController {

    @Autowired
    private UserGroupService userGroupService;

    @Autowired
    private UserGroupMemberService userGroupMemberService;

    @Autowired
    private UserGroupAdminService userGroupAdminService;

    @Autowired
    JWTUtil jwtUtil;

    @PreAuthorize("hasRole('admin')")
    @GetMapping()
    public ResultVO<Page<UserGroup>> getUserGroups( @RequestParam("page") String page,
                                                          @RequestParam("size") String size) {
            return ResultVO.success(userGroupService.getUserGroup(Integer.parseInt(page), Integer.parseInt(size)));
    }

    //批量添加
    @PostMapping("/{id}")
    public ResultVO<Boolean> insertUserToUserGroup(@PathVariable("id") String groupId,@RequestBody UserVO userVO){
        try {
            List<String> usersId = userVO.getUsersId();
            if (usersId == null || usersId.isEmpty()) {
                return ResultVO.success(false);
            }
            List<UserGroupMember> userGroupMembers = new ArrayList<>();
            for (String userId : usersId) {
                UserGroupMember userGroupMember = new UserGroupMember(groupId, userId);
                userGroupMembers.add(userGroupMember);
            }
            return ResultVO.success(userGroupMemberService.saveBatch(userGroupMembers));
        }
        catch (Exception e) {
            return ResultVO.error("添加用户中已有在用户组中");
        }
    }

    @PostMapping("/{id}/admin")
    public ResultVO<Boolean> grantAdminToUserGroup(@PathVariable("id") String groupId,@RequestBody UserVO userVO){
        try {
            List<String> usersId = userVO.getUsersId();
            if (usersId == null || usersId.isEmpty()) {
                return ResultVO.success(false);
            }
            List<UserGroupAdmin> userGroupAdmins = new ArrayList<>();
            for (String userId : usersId) {
                UserGroupAdmin userGroupAdmin = new UserGroupAdmin(groupId, userId);
                userGroupAdmins.add(userGroupAdmin);
            }
            return ResultVO.success(userGroupAdminService.saveBatch(userGroupAdmins));
        }
        catch (Exception e) {
            return ResultVO.error("添加管理用户重复");
        }
    }

    @GetMapping("/owns")
    public ResultVO<List<UserGroup>> getUserGroupById(){
        //从securityContext里面拿东西
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //String userId = user.getId();
        List<UserGroup> userGroups = userGroupAdminService.getManagedGroup(user.getId());
        return ResultVO.success(userGroups);
    }

    //创建用户组
    @PreAuthorize("hasAnyRole('admin','teacher')")
    @Transactional
    @PostMapping("")
    public ResultVO<Boolean> createUserGroup(@RequestBody UserGroup userGroup,HttpServletRequest request){
        //设置为随机UUID
        userGroup.setUserGroupId(UUID.randomUUID().toString());
        //设置更新日期
        userGroup.setUpdateTime(new Date());
        userGroupService.save(userGroup);
        //将请求发送者设为admin
        String authHeader = request.getHeader("Authorization");
        String token = authHeader.substring(7);
        //解析 JWT 拿到用户信息和角色
        User user = jwtUtil.parseJWT(token);
        UserGroupAdmin userGroupAdmin = new UserGroupAdmin(userGroup.getUserGroupId(),user.getId());
        userGroupAdminService.save(userGroupAdmin);
        UserGroupMember userGroupMember = new UserGroupMember(userGroup.getUserGroupId(),user.getId());
        userGroupMemberService.save(userGroupMember);
        return ResultVO.success(true);
    }

}
